package http;

import java.io.*;

/**
 * @author fengbo
 * @date 2018/10/20
 */
public class HttpResponse {

    private static final String ROOT_PATH = "C:\\Users\\MD-PC\\AppData\\Local\\Packages\\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\\LocalState\\rootfs\\home\\fb\\hexo\\public";
    private long contentLength;
    private String contentType = "text/html; charset=UTF-8";
    private File file;

    public HttpResponse(String uri) {
        if (uri.endsWith(".css")) {
            contentType = "text/css; charset=UTF-8";
        } else if (uri.endsWith(".js")) {
            contentType = "application/x-javascript";
        } else if (uri.endsWith(".svg") || uri.endsWith(".SVG")) {
            contentType = "image/svg+xml";
        } else if (uri.endsWith(".png") || uri.endsWith(".PNG")) {
            contentType = "image/png";
        } else if (uri.endsWith(".jpg") || uri.endsWith(".JPG")) {
            contentType = "application/x-jpg";
        } else {
            uri += "index.html";
        }
        file = new File(ROOT_PATH + uri);
        contentLength = file.length();
    }

    public String getHeader() {
        return "HTTP/1.1 200 OK\r\n" +
                "Server: OneFile 1.0\r\n" +
                "Content-length: " + contentLength + "\r\n" +
                "Content-type: " + contentType + "\r\n\r\n";
    }

    public byte[] getBody() {
        InputStream input = null;
        byte[] bytes;
        try {
            input = new FileInputStream(file);
            bytes = new byte[(int) contentLength];
            if (input.read(bytes) <= 0) {
                bytes = "error".getBytes();
            }
        } catch (IOException e) {
            bytes = "no found file".getBytes();
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }

    public long getContentLength() {
        return contentLength;
    }

    public void setContentLength(long contentLength) {
        this.contentLength = contentLength;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
}
